﻿namespace HZY.Framework.Core.ServerMetricMonitoring.Impl;

/// <summary>
/// unix 服务器指标监控服务
/// </summary>
public class UnixServerMetricMonitoringService : AbstractServerMetricMonitoringService, IServerMetricMonitoringService
{
    /// <summary>
    /// 获取计算机信息
    /// </summary>
    /// <returns></returns>
    public virtual RamInfo GetComputerInfo()
    {
        var memoryMetrics = this.GetRamInfo();
        memoryMetrics.CpuRate = Math.Ceiling(this.GetCpuRate().ToDouble()) + "%";
        return memoryMetrics;
    }

    /// <summary>
    /// 获取CPU使用率
    /// </summary>
    /// <returns></returns>
    public virtual string GetCpuRate()
    {
        return OperatingSystemUtil.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'").Trim();
    }

    /// <summary>
    /// 获取服务器运行时间
    /// </summary>
    /// <returns></returns>
    public virtual string GetRunTime()
    {
        string output = OperatingSystemUtil.Bash("uptime -s").Trim();

        return (DateTime.Now - output.ToDateTimeByString()).ToDayHourMinutesSeconds();
    }

    /// <summary>
    /// 获取磁盘信息
    /// </summary>
    /// <returns></returns>
    public virtual List<DiskInfo> GetDiskInfos()
    {
        var result = new List<DiskInfo>();

        try
        {
            string output = OperatingSystemUtil.Bash("df -m / | awk '{print $2,$3,$4,$5,$6}'");
            var arr = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            if (arr.Length == 0) return result;

            var rootDisk = arr[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
            if (rootDisk == null || rootDisk.Length == 0)
            {
                return result;
            }

            DiskInfo diskInfo = new()
            {
                DiskName = "/",
                TotalSize = long.Parse(rootDisk[0]) / 1024,
                Used = long.Parse(rootDisk[1]) / 1024,
                AvailableFreeSpace = long.Parse(rootDisk[2]) / 1024,
                AvailablePercent = decimal.Parse(rootDisk[3].Replace("%", ""))
            };
            result.Add(diskInfo);
        }
        catch
        {
            return result;
        }

        return result;
    }

    /// <summary>
    /// 获取内存指标信息
    /// </summary>
    /// <returns></returns>
    protected override RamInfo GetRamInfo()
    {
        string output = OperatingSystemUtil.Bash("free -m | awk '{print $2,$3,$4,$5,$6}'");
        var ramInfo = new RamInfo();
        var lines = output.Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);

        if (lines.Length <= 0) return ramInfo;

        if (lines != null && lines.Length > 0)
        {
            var memory = lines[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
            if (memory.Length >= 3)
            {
                ramInfo.Total = double.Parse(memory[0]);
                ramInfo.Used = double.Parse(memory[1]);
                ramInfo.Free = double.Parse(memory[2]);
            }
        }
        return ramInfo;
    }

}
